/*
 * @(#)User.java 2020/7/8 11:19 下午
 *
 * Copyright (c) 2010 by rayootech.com. All rights reserved.
 */
package com.nuctech.formlogin.model;

import cn.hutool.core.collection.CollUtil;
import lombok.*;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 用户表
 *
 * @author lilu
 * @date 2020/7/8 11:19 下午
 * @since 1.0.0
 */
@Data
@Builder
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@Entity(name = "t_user")
public class User implements UserDetails {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;
	private String username;
	private String password;
	private boolean accountNonExpired;
	private boolean accountNonLocked;
	private boolean credentialsNonExpired;
	private boolean enabled;
	@ManyToMany(fetch = FetchType.EAGER,cascade = CascadeType.PERSIST)
	private List<Role> roles;

	/**
	 * 返回用户的角色
	 *
	 * @author lilu
	 * @date 2020/7/8 11:26 下午
	 * @since 1.0.0
	 *
	 * @param
	 * @return java.util.Collection<? extends org.springframework.security.core.GrantedAuthority>
	 */
	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		List<SimpleGrantedAuthority> authorities = new ArrayList<>();
		if (CollUtil.isNotEmpty(this.roles)) {
			roles.forEach(r -> authorities.add(new SimpleGrantedAuthority(r.getName())));
		}
		return authorities;
	}
	/**
	 * 密码
	 *
	 * @author lilu
	 * @date 2020/7/8 11:29 下午
	 * @since 1.0.0
	 *
	 * @param
	 * @return java.lang.String
	 */
	@Override
	public String getPassword() {
		return this.password;
	}
	/**
	 * 用户名
	 *
	 * @author lilu
	 * @date 2020/7/8 11:29 下午
	 * @since 1.0.0
	 *
	 * @param
	 * @return java.lang.String
	 */
	@Override
	public String getUsername() {
		return this.username;
	}
	/**
	 * 账户是否未过期
	 *
	 * @author lilu
	 * @date 2020/7/8 11:29 下午
	 * @since 1.0.0
	 *
	 * @param
	 * @return boolean
	 */
	@Override
	public boolean isAccountNonExpired() {
		return this.accountNonExpired;
	}
	/**
	 * 账户是否未锁定
	 *
	 * @author lilu
	 * @date 2020/7/8 11:28 下午
	 * @since 1.0.0
	 *
	 * @param
	 * @return boolean
	 */
	@Override
	public boolean isAccountNonLocked() {
		return this.accountNonLocked;
	}
	/**
	 * 密码是否未过期
	 *
	 * @author lilu
	 * @date 2020/7/8 11:28 下午
	 * @since 1.0.0
	 *
	 * @param
	 * @return boolean
	 */
	@Override
	public boolean isCredentialsNonExpired() {
		return this.credentialsNonExpired;
	}
	/**
	 * 账户是否可用
	 *
	 * @author lilu
	 * @date 2020/7/8 11:27 下午
	 * @since 1.0.0
	 *
	 * @param
	 * @return boolean
	 */
	@Override
	public boolean isEnabled() {
		return this.enabled;
	}
}
